import "dart:collection";
import 'dart:convert';

import 'package:crypto/crypto.dart' as crypto;

/*
 * 1. queryParams -> key=value&k2=v2...
 * 2. body -> toString
 * 3. result = queryString&bodyString
 * 4. base64 encode (result)
 * 5. signature = md5 encode(base64 encode result)
 */
String generateSignature(options) {
  String params = '';
  if (options.queryParameters?.isNotEmpty == true) {
    List<String> sortKeys = options.queryParameters.keys.toList()..sort();
    params =
        sortKeys.map((key) => '$key=${options.queryParameters[key]}').join('&');
  }
  if (options.data?.isNotEmpty == true) {
    final sortedData = SplayTreeMap.from(options.data);
    params += params.isEmpty
        ? json.encode(sortedData)
        : '&${json.encode(options.data)}';
  }
  if (params.isEmpty) {
    return '';
  }

  String b64str = base64.encode(utf8.encode(params));
  return crypto.md5.convert(utf8.encode(b64str)).toString();
}
